# 加载工具
import pygame
import random
import os
from . import constants as C
# from . components import powerup
# from . import setup
class Game:
    def __init__(self, state_dict, start_state):
        self.screen = pygame.display.get_surface()
        self.clock = pygame.time.Clock()
        self.keys = pygame.key.get_pressed()
        self.state_dict = state_dict
        self.state = self.state_dict[start_state]
        # self.create_info_labels()  # 创建通用文字

    def update(self):
        if self.state.finished:  # 判断状态是否结束以及跳转
            game_info = self.state.game_info
            next_state = self.state.next
            self.state.finished = False
            self.state = self.state_dict[next_state]
            self.state.start(game_info)
        self.state.update(self.screen, self.keys)


    # def draw(self, surface):
    #     powerup.Powerup().draw(surface)

    def run(self):
        # 添加音频
        pygame.mixer.init()
        pygame.mixer.music.load('./resources/music/main_theme.ogg')
        pygame.mixer.music.play()
        # GRAPHICS = load_graphics('resources/graphics')
        while True:
            for event in pygame.event.get():

                if event.type == pygame.QUIT:
                    pygame.display.quit()
                    quit()
                elif event.type == pygame.KEYDOWN:
                    self.keys = pygame.key.get_pressed()
                elif event.type == pygame.KEYUP:
                    self.keys = pygame.key.get_pressed()
            # self.screen.fill((random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)))
            # image = get_image(GRAPHICS['mario_bros'], 145, 32, 16, 16, (0, 0, 0), 5)  # 左上角x, y, 宽，高，抠图底色，放大倍数
            # self.screen.blit(image, (300, 300))
            # state.update(self.screen, self.keys)  # 运行主菜单state界面，帧与帧之间调用主菜单自己的update方法
            self.update()

            pygame.display.update()
            self.clock.tick(60)  # 计时和控制游戏帧数， 1s渲染60张画面


def load_graphics(path, accept=('.jpg', '.png', '.bmp', '.gif')):  # 加载图片到字典  允许被读取的文件后缀
    graphics = {}  # 新建空字典
    for pic in os.listdir(path):  # 遍历文件夹
        name, ext = os.path.splitext(pic)  # 分拆成文件名+后缀
        if ext.lower() in accept:  # .lower()：把ext中字符串转化为小写
            img = pygame.image.load(os.path.join(path, pic))  # 载入
            if img.get_alpha():
                img = img.convert_alpha()
            else:
                img = img.convert()
            graphics[name] = img
    return graphics

def get_image(sheet, x, y, width, height, colorkey, scale):  # 获取图片信息 方框左上角坐标xy 宽，高  底色  放大倍数
    image = pygame.Surface((width, height))  # 和方框一样大的空图层
    image.blit(sheet, (0, 0), (x, y, width, height))  # 0,0 代表画到哪个位置，x,y,w,h代表sheet里哪个区域要取出来
    image.set_colorkey(colorkey)   # 对底色进行快速抠图
    image = pygame.transform.scale(image, (int(width*scale), int(height*scale)))  # 放大图片
    return image
